<script setup lang="ts">
import { ref, watch } from 'vue'
import allData from '../lib/pca.json'

export interface AreaItem {
  name: string
  code: string
  children?: AreaItem[]
}

export interface Data {
  name: string
  code: string
}

// 选择省份
const province = ref<string>('')
// 选择城市
const city = ref<string>('')
// 选择区域
const area = ref<string>('')

// 所有省市区乡数据
const all = ref(allData)
// 城市下拉框所有的值
const selectCity = ref<AreaItem[]>([])
// 区域下拉框所有的值
const selectArea = ref<AreaItem[]>([])

// 分发时间给父组件
const emits = defineEmits(['change'])

// 监听选择省份
watch(
  () => province.value,
  (val) => {
    if (val) {
      selectCity.value = all.value.find((item) => item.code === val)!.children
    }
    city.value = ''
    area.value = ''
  }
)
// 监听选择城市
watch(
  () => city.value,
  (val) => {
    if (val) {
      selectArea.value = selectCity.value.find((item) => item.code === val)!.children!
    }
    area.value = ''
  }
)

// 监听选择乡镇
watch(
  () => area.value,
  (val) => {
    if (!val) return
    const provinceData: Data = {
      code: province.value,
      name: province.value && all.value.find((item) => item.code === province.value)!.name
    }
    const cityData: Data = {
      code: city.value,
      name: city.value && selectCity.value.find((item) => item.code === city.value)!.name
    }
    const areaData: Data = {
      code: val,
      name: val && selectArea.value.find((item) => item.code === val)!.name
    }
    emits('change', {
      province: provinceData,
      city: cityData,
      area: areaData
    })
  }
)
</script>

<template>
  <div class="wrapper">
    <el-select clearable placeholder="请选择省份" v-model="province">
      <el-option v-for="item in all" :key="item.code" :value="item.code" :label="item.name" />
    </el-select>
    <el-select clearable :disabled="!province" placeholder="请选择城市" v-model="city">
      <el-option v-for="item in selectCity" :key="item.code" :value="item.code" :label="item.name" />
    </el-select>
    <el-select clearable :disabled="!province || !city" placeholder="请选择区域" v-model="area">
      <el-option v-for="item in selectArea" :key="item.code" :value="item.code" :label="item.name" />
    </el-select>
  </div>
</template>

<style lang="scss" scoped>
.wrapper {
  :deep(.el-select) {
    &:not(:first-child) {
      margin-left: 10px;
    }
  }
}
</style>
